from sqlalchemy import or_

from app.libs.error_code import ClientTypeError, Success
from app.libs.redprint import Redprint
from flask import jsonify

from app.models.user import User
from app.validators.forms import ClientForm, UserEmailForm, ArgsForm
from app.libs.enums import ClientTypeEnum

api = Redprint('client')


# 这是json格式body传参
@api.route('/register', methods=['POST'])
def create_client():
    form = ClientForm().validate_for_api()
    promise = {
        ClientTypeEnum.USER_EMAIL: __register_user_by_email
    }
    promise[form.type.data]()
    # 我们可以预知的异常 已知异常  抛出APIException
    return Success()


# 搞一个url传参的例子 http://127.0.0.1:5000/v1/client/args_get?email=21231211@qq.com&nickname=121133112
@api.route('/args_get', methods=['GET'])
def args_get():
    form = ArgsForm().validate_for_api()
    email=form.email.data
    nickname=form.nickname.data
    #users 返回的字段由User模型的keys方法所定义
    users=User.query.filter(or_(User.email==email,User.nickname==nickname)).all()
    #使用hide 方法把不想展示的字段隐藏掉
    users=[user.hide('auth','id').append('email') for user in users]
    return jsonify(users)




def __register_user_by_email():
    form = UserEmailForm().validate_for_api()
    User.register_by_email(form.nickname.data, form.account.data, form.secret.data)
